package com.chzc.fm.duotin.ui.other;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chzc.fm.duotin.utils.DuotinTask;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by BillSinla on 2016/6/7.
 */
public abstract class BaseFragment extends Fragment {

    /**
     * 子类的根布局
     * */
    protected View root;

    protected List<DuotinTask> mAsyncTasks = new ArrayList<>();


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root = inflater.inflate(getLayoutId(), container, false);
        return root;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initViews();
        initData();
        initEvent();
    }

    /*
    * 从子类获取布局id
    * */
    protected  abstract  int getLayoutId();

    /**
     * 视图初始化
     * */
    protected  abstract  void initViews();

    /**
     * 事件初始化
     * */
    protected abstract void initEvent();

    /**
     * 数据初始化
     * */
    protected abstract void initData();

    protected void putAsyncTask(DuotinTask task) {
        mAsyncTasks.add((DuotinTask) task.execute());
    }

    protected void clearAsyncTask() {
        Iterator<DuotinTask> iterator = mAsyncTasks
                .iterator();
        while (iterator.hasNext()) {
            DuotinTask asyncTask = iterator.next();
            if (asyncTask != null && !asyncTask.isCancelled()) {
                asyncTask.cancel(true);
            }
        }
        mAsyncTasks.clear();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        clearAsyncTask();
    }
}
